<template>
    <div class="content-view">
        <!-- <div class="test_div" @click="openCadViewer">打开Viewer看图纸</div> -->

        <div id="right-CAD" class="right-CAD"></div>
        <transition name="slide-fade" v-on:after-enter="afterRelationViewEnter"
            v-on:after-leave="afterRelationViewLeave">
            <CadTabel v-show="isShowMarkups == '2'" class="rightCadView" :markupFileDataList="markupFileDataList"
                :layerDataList="markupFileDataList.length <= 0 ? [] : layerDataList
                    " @onMarkupFileSelect="onMarkupFileSelect" @onShowLayerSelect="onShowLayerSelect"
                @onEditClick="openCadViewer" @onRefreshClick="onRefreshClick"></CadTabel>
        </transition>

        <el-dialog title="" :visible.sync="dialogVisible" :modal-append-to-body="false" width="30%">
            <span>マークアップデータが更新されました。</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="onMarkupChangeFromExternal">O K</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import * as svg_opt from "@/utils/svg_opt.js";
// import CadTabel from "./BHDialogCompontens/CadRightTabelCompontens";
import CadTabel from "./MT_Svg_right.vue";

import { getMarkUpFile, getSvgByFun, getThckMark } from "@/api/api";
import testBall from "@/utils/testdata/test_ball.js";
import { showLoading, hideLoading } from "@/utils/loading";
import eventBus from "@/eventBus/bus";

// 导出模块
export default {
    // 模块名字
    name: "CadViewForMS",

    // 模块数据
    components: {
        CadTabel,
    },

    props: {
        machineId: String,
        isShow: Boolean,
        isShowMarkups: String, // 1 ball  2 markup
    },

    data() {
        //数据
        return {
            svgSourceId: "",
            isSvgLoaded: false,
            testSvgIndex: 2,

            svgSourceUrl: "",
            sourceExt: "",
            sourceUrl: "",
            isSourcePic: false,

            dmgCode: -1,
            corrCode: "206",
            selectDate: "",
            pltCode: "",

            macNumb: "",
            pltName: "",
            macType: "",
            ballMarkerPosList: [],

            loadSvgWhenReShow: false,

            layerActiveIndex: -1,
            layerDataList: [],
            markupFileDataList: [],
            selectMarkerupFileData: {},

            // markup xml文件地址
            markupFileUrl: "",

            dialogVisible: false,

            cacheTableSelectData: null,

        };
    },

    watch: {
        isShow(val) {
            if (this.loadSvgWhenReShow && val) {
                this.reloadMachineDrawing();
                this.loadSvgWhenReShow = false;
            }
        },

        isShowMarkups(val) {
            if (val == "1") {
                this.showBallMaker();
            } else if (val == "2") {
                this.showMarkups();
            }
        },
    },

    methods: {
        loadSvgDataByRow(
            inDmgCode,
            inCorrCode, // 颜色筛选？
            inSelectDate, // 日期
            inPltCode, // pltcode

            inMacNumb,
            inPltName,
            inMacType,
            loadSvgWhenReShow,
            getVisualMarkType = 2
        ) {
            console.log(inDmgCode,
                inCorrCode, // 颜色筛选？
                inSelectDate, // 日期
                inPltCode, // pltcode

                inMacNumb,
                inPltName,
                inMacType,
                loadSvgWhenReShow, "222222222222222222222")
            // 18772 "colorOptionsValue" "LifeAssBaseVaule" 9 "100-001C" "fasd" 2 false
            this.macNumb = inMacNumb;
            this.pltName = inPltName;
            this.macType = inMacType;

            this.dmgCode = inDmgCode;
            this.corrCode = inCorrCode || '206';
            this.selectDate = inSelectDate;
            this.pltCode = inPltCode;

            this.loadSvgWhenReShow = loadSvgWhenReShow;
            // debugger
            this.ballMarkerPosList = [];
            this.layerDataList = [];
            this.markupFileDataList = [];
            this.selectMarkerupFileData = {};
            this.markupFileUrl = "";
            console.log("this.loadSvgWhenReShow", this.loadSvgWhenReShow);

            if (
                inDmgCode == null ||
                inSelectDate == null ||
                inPltCode == null
            ) {
                this.markupFileDataList = [];
                this.layerDataList = [];
                this.clearDraws();
                return;
            }

            if (!this.loadSvgWhenReShow) this.reloadMachineDrawing(getVisualMarkType);
        },

        reloadMachineDrawing(getVisualMarkType) {
            let _self = this;
            getSvgByFun({
                dmgCode: this.dmgCode,
                pltCode: this.pltCode,
                FunType: 7
            }).then(svgRes => {
                if (!svgRes || svgRes.data.code != 0) {
                    this.clearDraws();
                    hideLoading();
                    return;
                }


                _self.svgSourceUrl = "";

                let temp = svgRes.data.data[0];
                console.log('temp', temp);
                temp.drW_PASS = temp.path;
                temp.dwG_ID = temp.id;
                temp.origiN_EXT = temp.ext
                if (temp.path) {
                    let item = temp;
                    console.log(item.drW_PASS);
                    let inSourceUrl = item.drW_PASS;
                    _self.svgSourceId = item.dwG_ID;

                    let num = inSourceUrl.lastIndexOf(".") + 1;
                    _self.sourceExt = inSourceUrl.substring(num);
                    _self.sourceUrl = inSourceUrl;

                    let EXT = this.sourceExt
                    if (
                        EXT == "png" ||
                        EXT == "jpg" ||
                        EXT == "gif" ||
                        EXT == "bmp" ||
                        EXT == "jpeg" ||
                        EXT == "tif" ||
                        EXT == "tiff"
                    ) {
                        _self.isSourcePic = true;
                        _self.svgSourceUrl = require("@/assets/model/method-draw-image.svg");
                    } else {
                        _self.isSourcePic = false;
                        _self.svgSourceUrl = inSourceUrl;
                    }
                }
                // 获取markup文件
                getThckMark({
                    dmgCode: this.dmgCode,
                    macNumb: this.macNumb,
                    blnKbn: 1,
                    pltCode: this.pltCode,
                }).then(res => {

                    console.log(res);
                    if (!res.data.data || !res.data.data.length) {
                        res.data.data = [];
                    }
                    try {
                        res.data.data.forEach(item => {
                            item.poS_ORDR_Clone = item.poS_ORDR
                            item.poS_ORDR = Number(item.num)
                        })
                    } catch (error) {

                    }
                    _self.ballMarkerPosList = this.genThckBallMarkupsList(res.data.data);

                    _self.loadSvg(temp.origiN_EXT);
                    setTimeout(() => {
                        this.getVisualMarkType = 2;
                    }, 300);

                })
            })
            return
        },

        loadSvg(originExt) {
            if (!this.svgSourceUrl || this.svgSourceUrl == "") {
                this.clearDraws();
                return;
            }

            // showLoading();
            svg_opt.setSvgLineWidthRatio(1.5);
            svg_opt.setSvgBoundingBoxRatio(0, -20, 0.75);
            // svg_opt.setCanClickSelectMarkup(true,[1,2,3,4,5,6,7,8,9,10,11,12]);
            svg_opt.setCanClickSelectMarkup(true);
            svg_opt.setCanEditSelectMarkup(false);
            svg_opt.setCanFitPositionAndScale(true);
            svg_opt.setEditDotWidthRatio(3);
            svg_opt.setSelectCallBack(this.updateWhenMarkupSelected);
            svg_opt.AddSvg(
                this.svgSourceUrl,
                "right-CAD",
                this.onSvgMousePosChange,
                false,
                    0,
                    0,
                    originExt == "wmf" ? 1 : -1
            );
            svg_opt.SetSvgMouseMode(0);
            svg_opt.setLoadCallBack(this.onSvgLoaded);
        },

        onSvgLoaded(error) {
            hideLoading();
            if (error) {
                console.log(error);
                return;
            }
            this.isSvgLoaded = true;

            if (this.isSourcePic) {
                svg_opt.changeSvgElementData({
                    tagName: "img-content",
                    paramName: "xlink:href",
                    newValue: this.sourceUrl,
                });
            }

            this.requireMarkupFilesInfo();

            if (this.isShowMarkups == "1") {
                // svg_opt.genMarkupOrignDataFromExternalData(
                //     this.ballMarkerPosList
                // );
                this.showBallMaker();
            } else if (this.isShowMarkups == "2") {
                // this.loadMarkupFile(this.markupFileUrl);
                this.showMarkups();
            }
        },

        genThckBallMarkupsList(originData) {
            let reList = [];
            for (let i = 0; i < originData.length; i++) {
                let originItem = originData[i];
                let reListLength = reList.length;
                let reListLastItem =
                    reListLength > 0 ? reList[reListLength - 1] : null;

                // 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同
                if (
                    reListLength == 0 ||
                    reListLastItem.pos_no != originItem.poS_ORDR ||
                    (reListLastItem.pos_no == originItem.poS_ORDR &&
                        (reListLastItem.bln_kbn != originItem.blN_KBN ||
                            reListLastItem.bln_dtlno != originItem.blN_DTLNO))
                ) {
                    let ballTemp = {};
                    ballTemp.sId = originItem.poS_ORDR;
                    ballTemp.shapeType = Number(originItem.blN_TYPE) + 12;
                    ballTemp.showType = "trans";
                    ballTemp.showID = originItem.poS_ORDR;
                    ballTemp.lineColor = "#0000ff";
                    ballTemp.lineWidth = "5";
                    ballTemp.fontSize = originItem.blN_FNTSIZ;
                    ballTemp.fontName = originItem.blN_FNTNAM;
                    ballTemp.lineStyle = "0";
                    ballTemp.points = [];
                    ballTemp.bln_kbn = originItem.blN_KBN;
                    ballTemp.bln_dtlno = originItem.blN_DTLNO;

                    ballTemp.pos_no = originItem.poS_ORDR;
                    ballTemp.allText = originItem.poS_ORDR_Clone;
                    ballTemp.ballFillColor = "#00000000";

                    ballTemp.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });

                    reList.push(ballTemp);
                } else {
                    reListLastItem.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });
                }
            }
            return reList;
        },

        updateWhenMarkupSelected(e) {
            if (e == null) return;

            // debugger
            console.log("updateWhenMarkupSelected id = ", e.posOrder);
            if (Number(e.fEntType) >= 13) {
                svg_opt.changeSelectStatusById(e.posOrder);
            }
            this.$emit("onMarkupSelected", e.posOrder, this.macNumb);
        },

        setSelectedMarkup(e) {
            if (this.isShowMarkups == "1") {
                svg_opt.changeSelectStatusById(e);
            }
            this.cacheTableSelectData = e;
        },

        /**
         * 获取、更新图纸的层信息
         */
        updateLayersInfo() {
            // debugger;
            this.layerDataList = [];
            this.layerActiveIndex = JSON.parse(
                JSON.stringify(svg_opt.getActiveLayerIndex())
            );
            this.layerDataList = JSON.parse(
                JSON.stringify(svg_opt.getLayersData())
            );
        },

        /**
         * 请求markup xml 文件列表
         */
        requireMarkupFilesInfo() {
            // debugger;
            // let testFileID = "1f908560-e82b-4d76-8907-7e614b08f4c9";
            let testFileID = this.svgSourceId;
            let dataJson = {
                fileID: testFileID,
                markUpName: "",
                pageIndex: 1,
                pageSize: 1000,
                pltCode: this.pltCode,
            };

            getMarkUpFile(dataJson).then((res) => {
                if (res.data.code != 0) {
                    this.markupFileDataList = [];
                    return;
                }
                // debugger
                this.markupFileDataList = res.data.data;
            });
        },

        /**
         * 选择markup xml文件
         */
        onMarkupFileSelect(inFileData) {
            let testFileID = this.svgSourceId;
            let dataJson = {
                fileID: testFileID,
                markUpName: "",
                pageIndex: 1,
                pageSize: 1000,
                pltCode: this.pltCode,
            };

            getMarkUpFile(dataJson).then((res) => {
                let Data = res.data.data;
                for (var i = 0; i < Data.length; i++) {
                    if (Data[i].id == inFileData.id) {
                        inFileData.path = Data[i].path;
                        break;
                    }
                }

                console.log("onMarkupFileSelect inId = ");
                console.log(inFileData);
                this.selectMarkerupFileData = inFileData;

                if (inFileData == null || inFileData.path == null)
                    // this.loadMarkupFile("/markup_layers.xml");
                    this.markupFileUrl = "";
                // this.loadMarkupFile(inFileData.path);
                else this.markupFileUrl = inFileData.path;

                if (this.isShowMarkups == "2")
                    this.loadMarkupFile(this.markupFileUrl);
            });

        },
        /**
         * 选择markup layer图层
         */
        onShowLayerSelect(e) {
            console.log("onShowLayerSelect");
            console.log(e);
            svg_opt.setLayersData(e);
            svg_opt.updateMarkupsVisiableByData();
        },

        /**
         * 加载xml到图纸中
         */
        loadMarkupFile(path) {
            let res = svg_opt.loadMarkupsFromFile(path);
            if (!res) {
                this.$alert(this.$t("message.cadViewer.loadMarkupFileError"), '', {
                    confirmButtonText: 'OK',
                    type: 'warning',
                });
            }
            this.updateLayersInfo();
        },

        /**
         * 显示球标
         */
        showBallMaker() {
            // debugger;
            svg_opt.clearAllMarkups();
            svg_opt.genMarkupOrignDataFromExternalData(this.ballMarkerPosList);

            if (this.cacheTableSelectData) {
                svg_opt.changeSelectStatusById(this.cacheTableSelectData);
            }
        },

        /**
         * 显示markups
         */
        showMarkups() {
            svg_opt.clearAllMarkups();
            this.loadMarkupFile(this.markupFileUrl);
        },

        /**
         * 打开CadViewer页面
         */
        openCadViewer() {
            if (!this.svgSourceUrl || this.svgSourceUrl == "") {
                return
            }
            // debugger;
            var { href } = this.$router.resolve({
                name: "CAD",
                query: {
                    //     id: this.svgSourceId,
                    //     markupFileData: JSON.stringify(this.selectMarkerupFileData),
                    id: this.svgSourceId,
                    radioType: -1,
                    macNumb: this.$store.state.macNameb,
                    macCode: this.$store.state.macCode,
                },
            });

            let newWindow = window.open(href, "_blank");
        },

        onMarkupChangeFromExternal() {
            this.dialogVisible = false;
            this.onMarkupFileSelect(this.selectMarkerupFileData);
        },

        onRefreshClick() {
            this.ballMarkerPosList = [];
            this.layerDataList = [];
            this.markupFileDataList = [];
            this.selectMarkerupFileData = {};
            this.markupFileUrl = "";
            this.reloadMachineDrawing();
        },

        afterRelationViewEnter() {
            this.reloadMachineDrawing();
            console.log("--- afterRelationViewEnter ---");
        },

        afterRelationViewLeave() {
            this.reloadMachineDrawing();
            console.log("--- afterRelationViewLeave ---");
        },

        clearDraws() {
            this.svgSourceUrl = '';
            svg_opt.removeSvg();
        },
    },

    mounted() {
        // 监听
        let _self = this;
        window.onpageshow = function (event) {
            console.log("onpageshow ");
            console.log(event);
        };

        window.addEventListener("message", (event) => {
            // 我们能信任信息来源吗？
            // debugger
            if (event.origin !== window.location.origin) {
                alert("我们不能信任信息来源!!!!!");
                return;
            } else {
                if (event.data.func == "saveChangesOnMarkupFile") {
                    if (
                        _self.selectMarkerupFileData.id == event.data.data.xmlId
                    ) {
                        _self.dialogVisible = true;
                    }
                    // else if(event.data.data.id == this.svgSourceId && this.markupFileDataList.length == 0 ) {
                    //   _self.dialogVisible = true;
                    // }
                }
            }
            // console.log(event);
            // alert(event.data.message);
        });

        // this.loadSvgDataByRow(
        //   18886,
        //   "206",
        //   "2020-11",
        //   9,
        //   "100-E001",
        //   "サンプル装置",
        //   1,
        //   false
        // );
    },

    onShow() {
        console.log("CadViewForMS onshow");
    },
};
</script>

<style lang="scss" scoped>
.content-view {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: flex-start;
    background-color: #ffffff;

    .right-CAD {
        float: left;
        width: 100%;
        height: calc(100%);
    }

    .rightCadView {
        right: 0;
        width: 35%;
        height: calc(100%);
    }
}

.test_div {
    position: absolute;
    padding: 10rpx;
}

/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.slide-fade-enter-active {
    transition: all 0.3s ease;
}

.slide-fade-leave-active {
    transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter,
.slide-fade-leave-to

/* .slide-fade-leave-active for below version 2.1.8 */
    {
    transform: translateX(140px);
    opacity: 0;
}
</style>
